package com.examstack.portal.controller.action;

import com.examstack.common.domain.exam.Message;
import com.examstack.common.domain.question.CheckRecord;
import com.examstack.common.domain.question.KnowledgePoint;
import com.examstack.common.domain.question.Question;
import com.examstack.common.domain.question.QuestionTag;
import com.examstack.common.util.file.FileUploadUtil;
import com.examstack.portal.security.QuestionUtil;
import com.examstack.portal.security.UserInfo;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import com.examstack.portal.service.QuestionService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
public class QuestionAction {
    @Autowired
    private QuestionService questionService;
    /**
     * 添加试题
     *
     * @param question
     * @return
     */
    @RequestMapping(value = "/student/question-add/{fieldId}", method = RequestMethod.POST)
    public @ResponseBody Message addQuestion(@RequestBody Question question,@PathVariable int fieldId) {
        //QuestionUtil questionUtil = new QuestionUtil();
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Message message = new Message();
        //判断题目是否重复
        if(QuestionUtil.checkReaptQuestion(questionService,question.getQuestionContent().getTitle(),fieldId)){
            message.setResult("该试题已存在！");
            return message;
        }
        Gson gson = new Gson();
        question.setContent(gson.toJson(question.getQuestionContent()));
        question.setCreate_time(new Date());
        question.setCreator(userDetails.getUsername());
        //String content = question.getQuestionContent().getTitle();
        try {
            questionService.addQuestion(question);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            message.setResult("error");
            message.setMessageInfo(e.getClass().getName());
            e.printStackTrace();
        }

        return message;
    }

    //获取知识点
    @RequestMapping(value = "/question/get-knowledge-point/{fieldId}", method = RequestMethod.GET)
    public @ResponseBody
    Message getQuestionPointByFieldId(@PathVariable int fieldId) {
        Message message = new Message();
        HashMap<Integer, String> pointMap = new HashMap<Integer, String>();
        List<KnowledgePoint> pointList = questionService.getKnowledgePoint(fieldId, null);
        for (KnowledgePoint point : pointList) {
            pointMap.put(point.getPointId(), point.getPointName());
        }
        message.setObject(pointMap);
        return message;
    }

    /**
     * 获取试题详细信息
     * @param questionId
     * @return
     */
    @RequestMapping(value = "/student/question/question-detail/{questionId}", method = RequestMethod.GET)
    public @ResponseBody Message getQuestionDetail(@PathVariable("questionId") int questionId) {
        Message message = new Message();
        //UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        try {
            Question question = questionService.getQuestionDetail(questionId, 0);
            message.setObject(question);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            message.setResult(e.getCause().getMessage());
        }
        return message;
    }

    @RequestMapping(value = "/student/question/question-update", method = RequestMethod.POST)
    public @ResponseBody Message updateQuestion(@RequestBody String jsonStr){
        Message msg = new Message();
        Gson gson = new Gson();
        JsonParser parser = new JsonParser();
        JsonElement element = parser.parse(jsonStr);
        List<QuestionTag> questionTagList = gson.fromJson(element.getAsJsonObject().get("tags"), new TypeToken<ArrayList<QuestionTag>>(){}.getType());
        Question question = gson.fromJson(element.getAsJsonObject().get("question"), Question.class);
        try {
            questionService.updateQuestion(question, questionTagList);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            msg.setResult(e.getCause().getMessage());
        }
        return msg;
    }

    /**
     * 试题提交审核，同时添加审核记录
     * @param model
     * @param questionId
     * @param status
     * @return
     */
    @RequestMapping(value = "/student/question/update-question-status/{questionId}-{status}", method = RequestMethod.GET)
    public @ResponseBody Message updateQuestion(Model model, @PathVariable("questionId") int questionId
            , @PathVariable("status") int status) {

        // UserDetails userDetails = (UserDetails)
        // SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Message message = new Message();
        Question question = new Question();
        CheckRecord checkRecord = new CheckRecord();
        UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        try {
            //questionService.deleteQuestionByQuestionId(questionId);
            if(status<1||status>8){
                message.setResult("试题状态错误！");
                return message;
            }
            question.setId(questionId);
            question.setStatus(status);
            checkRecord.setCheckMan(userInfo.getUserid());
            checkRecord.setQuestionId(questionId);
            checkRecord.setOldStatus(1);
            checkRecord.setNewStatus(status);
            checkRecord.setCheckTime(new Date());
            questionService.updateQuestionStatus(question);
            questionService.addCheckRecord(checkRecord);
        } catch (Exception ex) {
            message.setResult(ex.getClass().getName());
        }

        return message;
    }

    /**
     * 删除试题草稿
     * @param model
     * @param questionId
     * @return
     */
    @RequestMapping(value = "/student/question/delete-question/{questionId}",method = RequestMethod.GET)
    public @ResponseBody Message deleteQuestion(Model model,@PathVariable("questionId") int questionId){
        Message message = new Message();
        Question question = new Question();
        question.setId(questionId);
        try{
            questionService.deleteByQuestionId(question);
        }catch (Exception e){
            message.setResult(e.getClass().getName());
        }
        return message;
    }

    /**
     * 试题上传图片
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/secure/upload-uploadify-img", method = RequestMethod.POST)
    public @ResponseBody String uploadImg(HttpServletRequest request, HttpServletResponse response) {
        UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<String> filePathList = new ArrayList<String>();
        try {
            filePathList = FileUploadUtil.uploadImg(request, response, userInfo.getUsername(),"question");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        if (filePathList.size() == 0) {
            return "系统错误";
        }

        return filePathList.get(0);
    }
}
